package com.base.cn.platform.os.service.manage.user.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 设置用户学员信息
 *
 * @author s.li
 * @create 2018-05-10-10:17
 */
@Component
public class SetUserDataService<E> {
    @Autowired
    private CusUserService cusUserService;

    /**
     * 设置用户数据
     * @param list 数据列表
     * @param setUserData 是否设置用户数据
     * @return List<E>
     */
    public List<E> setUserData(List<E> list,boolean setUserData){
        try {
            if(!ObjectUtils.isEmpty(list) && setUserData){
                StringBuffer userIds = new StringBuffer();
                for(E e : list){
                    Method userIdM = e.getClass().getMethod("getUserId");
                    if (!ObjectUtils.isEmpty(userIdM)){
                        BigDecimal userId = (BigDecimal) userIdM.invoke(e);
                        if(!ObjectUtils.isEmpty(userId)){
                            userIds.append(userId.toString()).append(",");
                        }
                    }
                }
                if(userIds.length()>0){
                    userIds.delete(userIds.length()-1,userIds.length());
                    Map<BigDecimal,Map<String,Object>> userMaps = cusUserService.queryCusUserMapByUserIds(userIds.toString(),false,false,false,false,false,false,false);
                    if (!ObjectUtils.isEmpty(userMaps)){
                        for(E e : list){
                            Method userIdM = e.getClass().getMethod("getUserId");
                            BigDecimal userId = (BigDecimal) userIdM.invoke(e);
                            if(userId.compareTo(new BigDecimal(0))==0){
                                continue;
                            }
                            Map<String,Object> user = userMaps.get(userId);
                            Method method = e.getClass().getMethod("setUser",Map.class);
                            user.remove("customerkey");
                            user.remove("password");
                            method.invoke(e,user);
                        }
                    }
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return list;
    }
}
